package com.tanhua.server.serivce;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.SettingsVo;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class SettingsService {

    @Reference
    private SettingsApi settingsApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private BlackListApi blackListApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Reference
    private UserApi userApi;


    //定义redis中储存的验证码的key前缀
    private String SMS_CHANGE_KEY = "SMS_CHANGE_KEY";

    /**
     * 接口名称：用户通用设置 - 读取
     */
    public ResponseEntity<Object> querySettings() {
        // 1. 获取当前认证后的用户
        User user = UserHolder.get();

        // 2. 根据用户id查询通知设置表 tb_settings
        Settings settings = settingsApi.findByUserId(user.getId());

        // 3. 根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(user.getId());

        // 4. 创建vo，封装返回结果
        SettingsVo settingsVo = new SettingsVo();
        // 来自于： db
        BeanUtils.copyProperties(settings,settingsVo);
        settingsVo.setPhone(user.getMobile());
        // 设置陌生人问题
        if (question == null) {
            settingsVo.setStrangerQuestion("你喜欢我吗？");
        } else {
            settingsVo.setStrangerQuestion(question.getTxt());
        }
        return ResponseEntity.ok(settingsVo);
    }

    /**
     * 接口名称：通知设置 - 保存
     */
    public ResponseEntity<Object> saveNotifications(Settings param) {
        //1. 获取认证后的用户
        Long userId = UserHolder.getUserId();

        //2. 先根据用户id查询通知设置表
        Settings settings = settingsApi.findByUserId(userId);
        if (settings == null) {
            // 没有找到数据，执行添加
            settings = new Settings();
            // 对象拷贝
            BeanUtils.copyProperties(param,settings);
            // 设置用户id
            settings.setUserId(userId);
            // 执行添加
            settingsApi.save(settings);
        } else {
            // 改用户的通知设置已经存在，执行修改
            settings.setPinglunNotification(param.getPinglunNotification());
            settings.setLikeNotification(param.getLikeNotification());
            settings.setGonggaoNotification(param.getGonggaoNotification());
            // 执行修改
            settingsApi.update(settings);
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 设置陌生人问题
     * @param content 页面传入的陌生人问题
     * @return
     */
    public ResponseEntity<Object> saveQuestion(String content) {
        //1. 获取认证后的用户
        Long userId = UserHolder.getUserId();

        //2. 根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(userId);

        //3. 判断
        if (question == null) {
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            // 执行保存
            questionApi.save(question);
        } else {
            question.setTxt(content);
            // 执行修改
            questionApi.update(question);
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：黑名单 - 翻页列表
     */
    public ResponseEntity<Object> blacklist(Integer page, Integer pagesize) {
        //1. 获取认证后的用户
        User user = UserHolder.get();

        //2. 根据用户id分页查询黑名单用户
        IPage<UserInfo> iPage = blackListApi.blacklist(page,pagesize,user.getId());

        //3. 封装返回结果
        PageResult pageResult = new PageResult(
                page,pagesize, (int) iPage.getTotal(),iPage.getRecords()
        );
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：黑名单 - 移除
     */
    public ResponseEntity<Object> deleteBlackUser(Long blackUserId) {
        // 获取当前登陆用户id
        Long userId = UserHolder.getUserId();
        // 调用dubbo服务，从黑名单列表中移除黑名单用户
        blackListApi.deleteBlackUser(userId,blackUserId);
        return ResponseEntity.ok(null);
    }


    /**
     * 接口名称：修改手机 -1、发送短信验证码
     */
    public ResponseEntity<Object> sendSmsToChange() {
        //获取登录用户
        User user = UserHolder.get();
        String phone = user.getMobile();

        //1. 生成6位随机数
        String code = (int) ((Math.random() * 9) + 1) * 10000 + "";
        //2. 发送短信验证码
        //smsTemplate.sendSms(phone, code);
        code = "123456";
        //3.验证码存储到redis中，key是: SMS_CHANGE_KEY_ + 手机号; 有效时间5分钟
        redisTemplate.opsForValue().set(SMS_CHANGE_KEY + phone, code, Duration.ofMinutes(5));

        return ResponseEntity.ok(null);


    }

    /**
     * 接口名称：接口名称：修改手机号 - 2 校验验证码
     */
    public ResponseEntity<Object> checkVerificationCode(String code) {
        //获取当前登录用户
        User user = UserHolder.get();

        String phone = user.getMobile();

        //从缓存数据库中获取验证码
        String redisCode = redisTemplate.opsForValue().get(SMS_CHANGE_KEY + phone);
        Boolean verification = true;
        if (redisCode == null || !redisCode.equals(code)) {
            verification = false;
        }
        redisTemplate.delete(SMS_CHANGE_KEY + phone);
        Map<String,Boolean> resultMap = new HashMap<>();
        resultMap.put("verification",verification);
        return ResponseEntity.ok(resultMap);
    }

    /**
     * 接口名称：修改手机号 - 3 保存
     * @param phone
     * @return
     */
    public ResponseEntity<Object> saveNewPhone(String phone) {
        User user = UserHolder.get();
        User user1 = userApi.findByMobile(phone);
        if (user1 != null) {
            return ResponseEntity.status(500).body(ErrorResult.mobileError());
        }

        user.setMobile(phone);
        userApi.saveNewPhone(user);
        return ResponseEntity.ok(null);
    }
}
